<template>
  <div>
    <a-drawer
      :open="props.open"
      title="详情"
      placement="right"
      @close="handleClose"
      width="500px"
    >
      <a-form :label-col="labelCol" :disabled="isForm" :model="formSate">
        <a-form-item label="子公司">
          <a-input
            style="width: 200px"
            disabled
            v-model:value="formSate.comNameLevel5"
          />
        </a-form-item>
        <a-form-item label="换热站">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.heatSourceName"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input
            style="width: 200px"
            v-model:value="formSate.heatSourceName"
          />
        </a-form-item>
        <a-form-item label="所属省份">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.provinceId"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-select
            ref="select"
            v-model:value="formSate.provinceId"
            style="width: 200px"
            @change="getCityData"
          >
            <a-select-option
              v-for="item in provinceList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属城市">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.cityId"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-select
            ref="select"
            v-model:value="formSate.cityId"
            style="width: 200px"
            @change="getAreaData"
          >
            <a-select-option
              v-for="item in cityList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属区域">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.countyId"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-select
            ref="select"
            v-model:value="formSate.countyId"
            style="width: 200px"
          >
            <a-select-option
              v-for="item in areaList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="小区">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.village"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input style="width: 200px" v-model:value="formSate.village" />
        </a-form-item>
        <a-form-item label="小区编号">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.villageCode"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input style="width: 200px" v-model:value="formSate.villageCode" />
        </a-form-item>
        <a-form-item label="经度">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.longitude"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input v-model:value="formSate.longitude" style="width: 200px" />
        </a-form-item>
        <a-form-item label="纬度">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.latitude"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input v-model:value="formSate.latitude" style="width: 70px" />
          <a-button type="primary" :icon="h(EnvironmentOutlined)" @click="onGps"
            >获取经纬度</a-button
          >
        </a-form-item>
        <a-form-item label="归属小区">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.belongVillage"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input v-model:value="formSate.belongVillage" style="width: 70px" />
        </a-form-item>
        <a-form-item label="收费方式">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.chargeMethod"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-select
            ref="select"
            v-model:value="formSate.chargeMethod"
            style="width: 200px"
          >
            <a-select-option value="地暖">地暖</a-select-option>
            <a-select-option value="散热器">散热器</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="建筑年限">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.buildingYear"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input style="width: 200px" v-model:value="formSate.buildingYear" />
        </a-form-item>
        <a-form-item label="小区地址">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.villageAddress"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input
            style="width: 200px"
            v-model:value="formSate.villageAddress"
          />
        </a-form-item>
        <a-form-item label="入网年度">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.networkYear"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input style="width: 200px" v-model:value="formSate.networkYear" />
        </a-form-item>
        <a-form-item label="总幢数(楼栋数)">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.totalBuildings"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input
            style="width: 200px"
            v-model:value="formSate.totalBuildings"
          />
        </a-form-item>
        <a-form-item label="总套数(房间数)">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.totaHouses"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input style="width: 200px" v-model:value="formSate.totaHouses" />
        </a-form-item>
        <a-form-item label="入住套数">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.checkingInHouses"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input
            style="width: 200px"
            v-model:value="formSate.checkingInHouses"
          />
        </a-form-item>
        <a-form-item label="建筑面积">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.buildingArea"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input style="width: 200px" v-model:value="formSate.buildingArea" />
        </a-form-item>
        <a-form-item label="实供面积">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.actualArea"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input style="width: 200px" v-model:value="formSate.actualArea" />
        </a-form-item>
        <a-form-item label="超高面积">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.ultraHighArea"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input
            style="width: 200px"
            v-model:value="formSate.ultraHighArea"
          />
        </a-form-item>
        <a-form-item label="物业电话">
          <template v-if="!isEdit && !isForm">
            <a-checkbox
              v-model:checked="selectedFields.propertyPhone"
              class="mr-2"
            ></a-checkbox>
          </template>
          <a-input
            style="width: 200px"
            v-model:value="formSate.propertyPhone"
          />
        </a-form-item>
      </a-form>
      <div class="text-right">
        <a-button type="primary" :icon="h(ScheduleFilled)"
         @click="handleChangeRecord" >小区信息修改记录</a-button
        >
      </div>
      <template #footer v-if="isForm">
        <a-space>
          <a-button
            type="primary"
            :icon="h(EditFilled)"
            @click="
              () => {
                isEdit = true;
                isForm = false;
                resetSelectedFields();
              }
            "
            v-if="props.auth.updates == 1"
            >修改</a-button
          >
          <a-button
            type="primary"
            :icon="h(EditFilled)"
            @click="
              () => {
                isEdit = false;
                isForm = false;
                resetSelectedFields();
              }
            "
            v-if="props.auth.updates == 1"
            >批量修改</a-button
          >
        </a-space>
      </template>
      <template #footer v-if="!isForm">
        <a-space>
          <a-button type="primary" @click="onsubmit">提交</a-button>
          <a-button
            @click="
              () => {
                isForm = true;
                handleClose();
              }
            "
            >取消</a-button
          >
        </a-space>
      </template>
      <a-modal
        v-model:open="Map"
        title="选取经纬度"
        :footer="null"
        width="800px"
      >
        <AMapPicker
          :initial-longitude="formSate.longitude"
          :initial-latitude="formSate.latitude"
          @confirm="handleConfirmLocation"
        />
      </a-modal>
      <a-modal
        :visible="changeRecord"
        title="修改记录"
        :footer="null"
        width="1200px"
        @cancel="changeRecord = false"
      >
        <a-table
          :columns="columns"
          :data-source="changeRecordData"
          :pagination="pagination"
        />
      </a-modal>
    </a-drawer>
  </div>
</template>
<script setup lang="ts">
import { h, ref, reactive, onMounted, watch } from 'vue';
import {
  EditFilled,
  ScheduleFilled,
  EnvironmentOutlined,
} from '@ant-design/icons-vue';
import AMapPicker from '#/components/Map/AMapPicker.vue';
import {
  getProvince,
  getCity,
  getArea,
  updateVillage,
  getVillageBatchOperation_four,
  getVillageChangeRecordApi,
} from '#/api';
import { message } from 'ant-design-vue';
import type { title } from 'process';
interface Props {
  selectedType: string;
  data: any;
  open: boolean;
  auth: Record<string, any>;
}

const props = defineProps<Props>();
// 获取省份
const provinceList = ref<any[]>([]);
// 获取城市
const cityList = ref<any[]>([]);
// 获取区域
const areaList = ref<any[]>([]);
const isEdit = ref(false);
const getProvinceData = async () => {
  const res = await getProvince();
  console.log('res', res);
  provinceList.value = res.map((item) => {
    return {
      id: Number(item.id),
      title: item.title,
    };
  });
  console.log(provinceList.value);
};
getProvinceData();
const getCityData = async (e: any) => {
  const res = await getCity(e);
  cityList.value = res.map((item) => {
    return {
      id: Number(item.id),
      title: item.title,
    };
  });
};
const getAreaData = async (e: any) => {
  const res = await getArea(e);
  areaList.value = res.map((item) => {
    return {
      id: Number(item.id),
      title: item.title,
    };
  });
};
const formSate = ref<Record<string, any>>({});

// 用于存储批量编辑时选中的字段
const selectedFields = reactive({
  comNameLevel5: false,
  heatSourceName: false,
  provinceId: false,
  cityId: false,
  countyId: false,
  village: false,
  villageCode: false,
  longitude: false,
  latitude: false,
  belongVillage: false,
  chargeMethod: false,
  buildingYear: false,
  villageAddress: false,
  networkYear: false,
  totalBuildings: false,
  totaHouses: false,
  checkingInHouses: false,
  buildingArea: false,
  actualArea: false,
  ultraHighArea: false,
  propertyPhone: false,
});

// 重置选中的字段
const resetSelectedFields = () => {
  Object.keys(selectedFields).forEach((key) => {
    selectedFields[key] = false;
  });
};

watch(
  () => props.data,
  async (newVal) => {
    console.log('newVal', newVal);
    // 确保newVal存在，然后将其赋值给formSate.value
    if (newVal) {
      formSate.value = { ...newVal };

      // 如果存在省份ID，则获取对应的城市列表
      if (formSate.value.provinceId) {
        await getCityData(formSate.value.provinceId);

        // 如果存在城市ID，则获取对应的区域列表
        if (formSate.value.cityId) {
          await getAreaData(formSate.value.cityId);
        }
      }
    }
  },
  { immediate: true }, // 立即执行一次，确保初始化时也能正确加载数据
);
const isForm = ref(true);
const Map = ref(false);
const labelCol = { style: { width: '120px' } };
const emit = defineEmits(['handleClose', 'refreshData']);
const handleClose = () => {
  emit('handleClose');
};

// 打开地图选择器
const onGps = () => {
  Map.value = true;
};

// 处理地图选择器确认事件
const handleConfirmLocation = (location: {
  longitude: number;
  latitude: number;
}) => {
  console.log('location', location);
  formSate.value.longitude = location.longitude.toString();
  formSate.value.latitude = location.latitude.toString();
  Map.value = false;
};
const onsubmit = () => {
  if (isEdit.value) {
    const data = {
      ...formSate.value,
      // 直接使用表单中已有的provinceId、cityId和countyId字段
      regionId: props.data.regionId,
      applicationReason: props.data.applicationReason,
      attachmentLocation: props.data.attachmentLocation,
      operateObject: props.data.operateObject,
    };
    // 单独修改逻辑
    updateVillage(data).then((res) => {
      console.log('单独修改', res);
      if (res === '修改成功!') {
        message.success(res);
        isForm.value = true;
        emit('refreshData'); // 通知父组件刷新数据
        handleClose();
      } else {
        message.error(res || '修改失败!');
      }
    });
  } else {
    // 批量修改逻辑
    // 创建一个只包含选中字段的对象
    const selectedData = {};
    Object.keys(selectedFields).forEach((key) => {
      if (selectedFields[key]) {
        selectedData[key] = formSate.value[key];
      }
    });

    // 检查是否有选中的字段
    if (Object.keys(selectedData).length === 0) {
      message.warning('请至少选择一个要修改的字段');
      return;
    }

    // 这里需要实现批量修改的API调用
    console.log('批量修改的数据', selectedData);
    const data = {
      ...selectedData,
      regionId: props.data.regionId,
      applicationReason: props.data.applicationReason,
      attachmentLocation: props.data.attachmentLocation,
      operateObject: props.data.operateObject,
    };
    // 示例：调用批量修改API
    getVillageBatchOperation_four(data).then((res) => {
      if (res.data.code === 200) {
        message.success('批量修改成功!');
        isForm.value = true;
        emit('refreshData'); // 通知父组件刷新数据
        handleClose();
      } else {
        message.error(res.message || '批量修改失败!');
      }
    });

    // 临时提示，实际项目中应替换为真实API调用
    // message.success('批量修改功能已触发，请实现对应的API');
    // isForm.value = true;
    // handleClose();
  }
};
const changeRecord = ref(false);
const changeRecordData = ref([]);
const columns = [
  {
    title: '所属省',
    dataIndex: 'province',
    align: 'center',
  },
  {
    title: '所属市',
    dataIndex: 'city',
    align: 'center',
  },
  {
    title: '所属区/县',
    dataIndex: 'county',
    align: 'center',
  },
  {
    title: '所属换热站',
    dataIndex: 'heatExchangeStationName',
    align: 'center',
  },
  {
    title: '小区名称',
    dataIndex: 'village',
    align: 'center',
  },
  {
    title: '经度',
    dataIndex: 'longitude',
    align: 'center',
  },
  {
    title: '纬度',
    dataIndex: 'latitude',
    align: 'center',
  },
  {
    title: '收费方式',
    dataIndex: 'chargeMethod',
    align: 'center',
  },
  {
    title: '建筑年限',
    dataIndex: 'buildingYear',
    align: 'center',
  },
  {
    title: '归属小区',
    dataIndex: 'belongVillage',
    align: 'center',
  },
  {
    title: '小区地址',
    dataIndex: 'villageAddress',
    align: 'center',
  },
  {
    title: '是否完成',
    dataIndex: 'isCompleted',
    key: 'isCompleted',
  },
  {
    title: '操作类型',
    dataIndex: 'operType',
    key: 'operType',
  },
  {
    title: '操作人',
    dataIndex: 'reporter',
    key: 'reporter',
  },
  {
    title: '操作时间',
    dataIndex: 'operTime',
    key: 'operTime',
  },
];
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    getVillageChangeRecordApi({
      page: page,
      limit: pageSize,
      villageID: props.data.villageId,
    }).then((res) => {
      // console.log('res', res);
      changeRecordData.value = res.data.data;
      pagination.total = res.data.count;
    });
  },
});
const handleChangeRecord = () => {
  changeRecord.value = true;
  getVillageChangeRecordApi({
    page: pagination.current,
    limit: pagination.pageSize,
    villageID: props.data.villageId,
  }).then((res) => {
    // console.log('res', res);
    changeRecordData.value = res.data.data;
    pagination.total = res.data.count;
  });
};
</script>
<style scoped>
.mr-2 {
  margin-right: 8px;
}
</style>
